package com.projects.modular.system.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.projects.modular.realty.entity.RegisteredUsers;
import com.projects.modular.realty.service.RegisteredUsersService;
import com.projects.modular.system.entity.SystemStatus;
import com.projects.modular.system.entity.Task;
import com.projects.modular.system.service.SseService;
import com.projects.modular.system.service.TaskService;
import com.projects.modular.system.utils.DateUtil;
import com.projects.modular.system.utils.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class SseScheduledTask {

    @Autowired
    private SseService sseService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RegisteredUsersService registeredUsersService;

    private static final Logger log = LoggerFactory.getLogger(SseScheduledTask.class);

    //微信小程序id
    private final static String appId = "wx39d95a2c0218c00f";
    //微信小程序密钥
    private final static String appSecret = "66eae34feaaf87c0e7faa13c0cb7f87c";
    //模板id
    private final static String templateId = "WpDIzPO4s5o_DUkk2_pCykjyyy1skRC1eCNRXHKBCFQ";
    //消息内容-温馨提示
    private final static String warmTip = "该去小程序进行测评啦!";
    //跳转页面地址
    private final static String pageUrl = "pages/home/home";
    //获取token接口
    private final static String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
    //发送消息接口
    private final static String sendWxUserMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";


    /**
     * 每10秒向所有连接的客户端推送当前时间
     */
//    @Scheduled(fixedRate = 10000)
//    @Scheduled(cron = "0/10 * * * * ?")
    public void sendTimeNotification() {
        System.out.println("Sending time notification...");
        String message = "Current server time: " + new Date();
        sseService.broadcastMessage("time_update", message);
    }

    /**
     * 每5分钟发送系统状态信息
     */
    @Scheduled(fixedRate = 600000)
    public void sendSystemStatus() {
        QueryWrapper<Task> taskWrapper = new QueryWrapper<>();
        taskWrapper.lambda().eq(Task::getSendStatus, 0);
        List<Task> list = taskService.list(taskWrapper);
        if (list != null && !list.isEmpty()){
            log.info("开始发送系统状态信息::list:", JSON.toJSONString(list));
            // 查询相关用户
            List<String> userNameList = list.stream().map(Task::getUserName).collect(Collectors.toList());
            List<RegisteredUsers> userList = registeredUsersService.list(new QueryWrapper<RegisteredUsers>().lambda().in(RegisteredUsers::getUserName, userNameList));
            for (Task task : list) {
                // 根据用户名查询用户信息
                RegisteredUsers user = userList.stream().filter(u -> u.getUserName().equals(task.getUserName())).findFirst().orElse(null);
                // 如果用户是已订阅状态 发送消息
                if (user != null && user.getOpenId() != null && user.getSubscribeStatus() == 1 && task.getSendTime().getTime() < System.currentTimeMillis()) {
//                    registeredUsersService.updateSubscribeStatus(0, task.getUserName(), null);
                    user.setSubscribeStatus(0);
                    user.setOpenId(null);
                    String sendMessage = sendMessage(user.getOpenId());
                    task.setSendStatus(1);
                }
            }
            // 更新任务状态
            registeredUsersService.updateBatchById(userList);
            taskService.updateBatchById(list);
        }
    }


    public static String sendMessage(String openUserId) {
        //获取token
        String accessTokenResult = HttpClientUtil.doGet(getTokenUrl);
        String accessToken = JSONObject.parseObject(accessTokenResult).getString("access_token");
        SendMsgToWxUserRequestDTO sendMsgToWxUserRequestDTO = new SendMsgToWxUserRequestDTO();
        sendMsgToWxUserRequestDTO.setAccessToken(accessToken);
        sendMsgToWxUserRequestDTO.setTouser(openUserId);
        sendMsgToWxUserRequestDTO.setTemplate_id(templateId);
        JSONObject key = new JSONObject();
        //温馨提醒
        JSONObject thingfValue = new JSONObject();
        thingfValue.put("value", warmTip);
        key.put("thing3", thingfValue);
        //当前时间
        JSONObject date2 = new JSONObject();
        date2.put("value", DateUtil.dateToString(new Date(), DateUtil.DATETIME_FORMATTER));
        key.put("date2", date2);
        sendMsgToWxUserRequestDTO.setData(key);
        sendMsgToWxUserRequestDTO.setPage(pageUrl);
        String sendMessageUrl = sendWxUserMsgUrl + accessToken;
        log.info("发送消息参数:{}", JSONObject.toJSONString(sendMsgToWxUserRequestDTO));
        String s = HttpClientUtil.doPost(sendMessageUrl, JSONObject.toJSONString(sendMsgToWxUserRequestDTO));
        log.info("发送消息参数,返回值:{}", s);
        return s;
    }


}